package com.fancy.net
{
	import com.fancy.framework.BundleContext;
	import com.fancy.framework.BundleLeader;
	import com.fancy.framework.BundleModuleName;
	import com.fancy.framework.BundleNotice;
	import com.fancy.net.forward.ForwardList;
	import com.fancy.net.notice.NetNoticeType;
	import com.fancy.net.sock.SockConn;
	import com.fancy.net.sock.SockCrossDomain;
	import com.fancy.net.stream.StreamDic;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.system.Security;
	import flash.system.System;
	import flash.utils.ByteArray;
	
	public class NetLeader extends BundleLeader
	{
		public function NetLeader(context:BundleContext)
		{
			super(context);
		}
		
		override public function getModuleName():String
		{
			return BundleModuleName.NET_CONNECTION;
		}
		
		override public function getLevel():uint
		{
			return 4;
		}
		
		override public function initializeLeader():void
		{
			trace("NetLeader::initializeLeader()");
			ForwardList.initialize();
			StreamDic.initialize();
			tryConnectToServer();
		}
		
		override public function execute(notice:BundleNotice):void
		{
			trace("NetLeader::execute ", notice.type, notice.name, notice.body);
			switch(notice.type)
			{
			case NetNoticeType.SEND_TO_SRV:
				sendToSrvHandler(notice);
				break;
			}
		}
		
		/** 安全沙箱跨域请求权限socket */
		private var _sockCross:SockCrossDomain = new SockCrossDomain();
		/** 主socket */
		private var _sockConn:SockConn = new SockConn();
		/** 尝试连接服务器 */
		private function tryConnectToServer():void
		{
			trace("NetLeader::tryConnectToServer()");
			_sockCross.addEventListener(Event.CONNECT, domainLicenseBack);
			var destIP:String = String(context.getConfig(BundleContext.CFG_DEST_IP));
			var domainPort:int = int(context.getConfig(BundleContext.CFG_DOMAIN_PORT));
			_sockCross.exeConnect(destIP, domainPort);
		}
		
		/** 请求跨域许可返回 */
		private function domainLicenseBack(event:Event):void
		{
			trace("NetLeader::domainLicenseBack(event:Event)");
			_sockCross.exeClose();
			var destIP:String = String(context.getConfig(BundleContext.CFG_DEST_IP));
			var connPort:int = int(context.getConfig(BundleContext.CFG_CONN_PORT));
			_sockConn.exeConnect(destIP, connPort);
		}
		
		private function sendToSrvHandler(notice:BundleNotice):void
		{
			_sockConn.sendNoticeToServer(notice);
		}
		
	}
}